package com.huluobo.a2206parkdemo.visitor

import android.content.Intent
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2206parkdemo.R
import com.huluobo.a2206parkdemo.adapter.VisitorAdapter
import com.huluobo.a2206parkdemo.databinding.ActivityVisitorBinding
import com.huluobo.base.bean.VisitorBean
import com.huluobo.base.bean.VisitorBeanItem
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import com.tencent.smtt.utils.l
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.parse
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class VisitorActivity : BaseActivity<ActivityVisitorBinding, VisitorViewModel>() {
    private lateinit var visitorAdapter: VisitorAdapter
    private lateinit var visitorBeanItem: VisitorBeanItem
    override fun initData() {
        vm.getAllVisitorSuccess.observe(this) {
            val list = Gson().fromJson(it, VisitorBean::class.java)
            visitorAdapter.data.clear()
            visitorAdapter.data.addAll(list)
            visitorAdapter.notifyDataSetChanged()
        }

        vm.deleteVisitorSuccess.observe(this) {
            ToastUtils.showLong("删除成功")
            visitorAdapter.remove(visitorBeanItem)
        }
    }

    override fun onResume() {
        super.onResume()
        val map = mutableMapOf<String, Int>()
        map[Const.PARAM_USER_ID] = 0
        val json = Gson().toJson(map)
        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
        vm.getAllVisitor(body)
    }

    override fun initView() {
        binding.visitorHeader.headerTitle.text = "来访预约"
        binding.visitorHeader.headerBack.setOnClickListener { finish() }
        binding.visitorHeader.headerAdd.visibility = View.VISIBLE
        binding.visitorHeader.headerAdd.setOnClickListener {
            val intent = Intent(this, AddVisitorActivity::class.java)
            startActivity(intent)
        }

        binding.visitorRv.layoutManager = LinearLayoutManager(this)
        visitorAdapter = VisitorAdapter()
        binding.visitorRv.adapter = visitorAdapter

        visitorAdapter.addChildClickViewIds(R.id.item_visitor_delete_iv)
        visitorAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.item_visitor_delete_iv) {
                visitorBeanItem = visitorAdapter.data[position]
                val map = mutableMapOf<String, Int>()
                map[Const.PARAM_VISITOR_ID] = visitorAdapter.data[position].visitorId

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)

                vm.deleteVisitor(body)
            }
        }
    }
}